﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Vtron.HipcConfigurationTools.Core;
using Vtron.HipcConfigurationTools.Domain;

namespace Vtron.HipcConfigurationTools
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private int size = 1000;
        public MainWindow()
        {
            InitializeComponent();

            List<CodecInfo> codecInfoes = DataStore.GetFolderListing();
            CodecListViewModel = new CodecListViewModel();
            CodecListViewModel.HeaderInfo = "列表";
            foreach (CodecInfo codecInfo in codecInfoes)
            {
                CodecListViewModel.CodecInfoes.Add(codecInfo);
            }
            codecTabItem.DataContext = CodecListViewModel;

            CodecConnectViewModel CodecConnectViewModel = new CodecConnectViewModel();
            CodecConnectViewModel.HeaderInfo = "连接";
            codecConnectTabItem.DataContext = CodecConnectViewModel;

            //UpdateTools();
        }

        public void UpdateTools()
        {
            Utils.IP = "10.4.1.182";
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            int checkSum = 0;
            int fileLen = 0;
            byte[] filebt = null;
            if (openFileDialog.ShowDialog() == true)
            {
                string fName = openFileDialog.FileName;
                FileStream fs = new FileStream(fName, FileMode.Open);
                filebt = new byte[fs.Length];
                BinaryReader br = new BinaryReader(fs);
                fileLen = Convert.ToInt32(fs.Length);
                filebt = br.ReadBytes(fileLen);

                for (int i = 0; i < filebt.Count(); i++)
                {
                    checkSum += filebt[i];
                }
            }

            NET_TCP_HEAD_TAG tcpHead = new NET_TCP_HEAD_TAG();
            tcpHead.cmd = 0x4000;
            tcpHead.fileLen = 16;

            Start start = new Start();
            start.head = tcpHead;
            start.fileLen = fileLen;
            start.checkSum = checkSum;

            object response = new object();
            byte[] Message = Utils.StructToBytes(start);
            TcpClient socket = new TcpClient();

            IPHostEntry host = Dns.GetHostEntry(Utils.IP);
            IPAddress[] ipAddress = host.AddressList;

            socket.Connect(ipAddress, Utils.UPDATAPORT);


            NetworkStream ns = socket.GetStream();
            ns.Write(Message, 0, Message.Length);
            byte[] Recv = new byte[1024];
            int NumberOfRecv = 0;
            IList<byte> newRecv = new List<byte>();
            ns.ReadTimeout = 3000;
            do
            {
                NumberOfRecv = ns.Read(Recv, 0, Recv.Length);
                for (int i = 0; i < NumberOfRecv; i++)
                {
                    newRecv.Add(Recv[i]);
                }
            }
            while (ns.DataAvailable);
            byte[] resultRecv = new byte[newRecv.Count];
            newRecv.CopyTo(resultRecv, 0);

            response = Utils.BytesToStruct(resultRecv, typeof(Return));

            Return ret = (Return)response;


            tcpHead.cmd = 0x4001;
            tcpHead.fileLen = size + 12;
            Send send = new Send();
            send.head = tcpHead;

            newm(send, filebt, ns, socket, 0);

            //socket.Close();
            //ns.Close();
        }


        public void newm(Send send, byte[] filebt, NetworkStream ns, TcpClient socket, int k)
        {
            Thread.Sleep(20);
            send.id = k + 1;
            if (k == filebt.Count() / size)
            {
                send.data = filebt.Skip(k * size).Take(filebt.Count() - k * size).Concat(new byte[size - filebt.Count() + k * size]).ToArray();
                send.head.fileLen = filebt.Skip(k * size).Take(filebt.Count() - k * size).Count() + 12;
                byte[] Message = Utils.StructToBytes(send);
                ns = socket.GetStream();
                ns.BeginWrite(Message, 0, Message.Length, (ia) =>
                {
                    Thread.Sleep(20);
                    send.head.cmd = 0x4002;
                    send.head.fileLen = 12;

                    Message = Utils.StructToBytes(send);
                    ns = socket.GetStream();

                    IAsyncResult ar = ns.BeginWrite(Message, 0, Message.Length, (ia1) =>
                    {
                        var Recv = new byte[1024];
                        var NumberOfRecv = 0;
                        var newRecv = new List<byte>();
                        ns.ReadTimeout = 3000;
                        do
                        {
                            NumberOfRecv = ns.Read(Recv, 0, Recv.Length);
                            for (int i = 0; i < NumberOfRecv; i++)
                            {
                                newRecv.Add(Recv[i]);
                            }
                        }
                        while (ns.DataAvailable);
                        var resultRecv = new byte[newRecv.Count];
                        newRecv.CopyTo(resultRecv, 0);
                        var response = Utils.BytesToStruct(resultRecv, typeof(Return));
                        var ret = (Return)response;
                    }, null);
                }, ns);
            }
            else
            {
                send.data = filebt.Skip(k * size).Take(size).ToArray();

                byte[] Message = Utils.StructToBytes(send);
                ns = socket.GetStream();

                IAsyncResult ar = ns.BeginWrite(Message, 0, Message.Length, (ia) =>
                {
                    newm(send, filebt, ns, socket, ++k);
                }, null);
            }
        }

        public CodecListViewModel CodecListViewModel { get; set; }

        public void SaveCodec()
        {
            List<CodecInfo> codecInfoes = new List<CodecInfo>();
            codecInfoes.AddRange((codecTabItem.DataContext as CodecListViewModel).CodecInfoes);
            DataStore.SaveFolderListing(codecInfoes);
        }

        //public void ShowDetails()
        //{
        //    row.Height = new GridLength(3, GridUnitType.Star);
        //    Button submitButton = (Button)ActionContent.Template.FindName("SubmitButton", ActionContent);
        //    submitButton.IsEnabled = false;

        //    Button cancelButton = (Button)ActionContent.Template.FindName("CancelButton", ActionContent);
        //    cancelButton.Click += cancelButton_Click;

        //ComboBox encodedCombo = (ComboBox)ActionContent.Template.FindName("EncodedCombo", ActionContent);
        //List<CodecInfo> encodedCodecList = new List<CodecInfo>();
        //encodedCodecList.AddRange(CodecListViewModel.CodecInfoes.Where(c => c.CodecType == "编码器"));
        //encodedCombo.ItemsSource = encodedCodecList;
        //encodedCombo.SelectionChanged += encodedCombo_SelectionChanged;

        //ComboBox decodeCombo = (ComboBox)ActionContent.Template.FindName("DecodeCombo", ActionContent);
        //List<CodecInfo> decodeComboList = new List<CodecInfo>();
        //decodeComboList.AddRange(CodecListViewModel.CodecInfoes.Where(c => c.CodecType == "解码器"));
        //decodeCombo.ItemsSource = decodeComboList;
        //decodeCombo.SelectionChanged += decodeCombo_SelectionChanged;
        //}

        //private void encodedCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    ComboBox decodeCombo = (ComboBox)ActionContent.Template.FindName("DecodeCombo", ActionContent);
        //    if (decodeCombo.SelectedItem != null)
        //    {
        //        Button submitButton = (Button)ActionContent.Template.FindName("SubmitButton", ActionContent);
        //        submitButton.IsEnabled = true;
        //    }
        //}

        //private void decodeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    ComboBox encodedCombo = (ComboBox)ActionContent.Template.FindName("EncodedCombo", ActionContent);
        //    if (encodedCombo.SelectedItem != null)
        //    {
        //        Button submitButton = (Button)ActionContent.Template.FindName("SubmitButton", ActionContent);
        //        submitButton.IsEnabled = true;
        //    }
        //}

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Button submitButton = (Button)ActionContent.Template.FindName("SubmitButton", ActionContent);
            submitButton.IsEnabled = false;
            HiddenDetails();
        }

        public void HiddenDetails()
        {
            row.Height = new GridLength(0);
        }
    }
}
